package com.mall.sun.handler;



import com.mall.sun.model.vo.ResultVO;
import com.mall.sun.utils.JsonUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * description: 登录失败的处理逻辑 <br>
 * date: 2021/8/3 16:04 <br>
 * author: ztz <br>
 * version: 1.0 <br>
 * @author Tansty
 */
@Configuration
public class CustomizeAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        ResultVO result = new ResultVO() ;
        if(e instanceof BadCredentialsException){
            result.setCode(405);
            result.setMsg("密码错误");
            result.setData("error");
        }else if (e instanceof InternalAuthenticationServiceException){
            result.setCode(405);
            result.setMsg("用户不存在");
            result.setData("error");
        }else{
            result.setCode(405);
            result.setMsg("其他错误");
            result.setData("error");
        }
        //处理编码方式，防止中文乱码的情况
        httpServletResponse.setContentType("text/json;charset=utf-8");
        //塞到HttpServletResponse中返回给前台
        httpServletResponse.getWriter().write(JsonUtil.obj2String(result));
    }
}
